<?php
/**
 * Class C_Order 客户端订单资源
 */
namespace V1;
use Biz\ChannelHandler;

class  C_Order extends \ResourceClass
{
    function __construct()
    {
        require_once(ROOT . 'lib/AliPay/AliPayConfig.php');
        require_once(ROOT . 'lib/WxPay/WxPay.php');
    }

    public $isActive = true;
    public $remark = '获取客户端订单列表,取消订单';

    public function get(array $req, array $post, &$result)
    {
        try {
            /* 授权验证【开始】 */
            if (!isset($req['uid'])) {
                return 'require user id ';
            }
            if (!isset($req['userType'])) {
                return 'require user type';
            }
            if (!isset($req['k']) || !isset($req['t'])) {
                return 'data error';
            }
            if (!array_key_exists('id', $req) || empty($req['id'])) {
                return 'require resource id';
            }

            $user_cls = \Biz\UserHandler::getById($req['userType'], $req['uid']);
            if (!is_object($user_cls) || $user_cls->getEnterpriseId() == false) {
                return 'data error';
            }
            $enterprise_id = $user_cls->getEnterpriseId();

            /* 授权验证*/
            if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $enterprise_id, $req['id'] . $req['t'], $req['k']) == false) {
                   return 'data illegal';
            }

            $is_sku = (isset($req['is_sku']) && $req['is_sku'] == 1) ? 1 : 0;
            $order_handler = new \Biz\OrderHandler();
            $order_cls = $order_handler->getOrderAndDetailByOrderId((intval($req['id'])));
            $result = $this->orderFiled($order_cls, $is_sku);
        } catch (Exception $e) {
            return $e->getMessage();
        }

    }

    public function post(array $req, array $post, &$result)
    {
        try {
            /* 授权验证【开始】 */
            if (!isset($req['uid'])) {
                return 'require user id ';
            }
            if (!isset($req['userType'])) {
                return 'require user type';
            }
            if (!isset($req['k']) || !isset($req['t'])) {
                return 'data error';
            }
            if (!array_key_exists('payload', $post)) {
                return 'require payload';
            }

            $data = base64_decode($post['payload']);
            @parse_str($data, $data);
            $orderList = substr($data['orderList'], 0, strlen($data['orderList']));
            $orderDetailsArray = self::order_product_array($orderList);
            if ($orderDetailsArray == false ) {
                return '至少选着一个商品！！！';
            }
            if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $orderDetailsArray[0]['enterprise_id'], $req['t'] . $post['payload'], $req['k']) == false) {
                   return 'data illegal';
            }

            //解析payload
            $detail_list = array();
            foreach ($orderDetailsArray as $k => $v) {
                $order_detail_cls = new \Cls\Order\Detail();
                $order_detail_cls->create($v['product_id'], $v['sku_id'], $v['product_num']);
                $detail_list[] = $order_detail_cls;

            }
            $customer_hand = new \Biz\EnterpriseCustomerHandler();
            $customer_cls = $customer_hand::getEnterpriseCustomerById($orderDetailsArray[0]['enterprise_id'], $req['uid']);

            // 操作库存前判断企业是否开启仓库审核
            if (\Biz\Workflow\RelevanceGlobalConfig::isEnterpriseCheckStock($orderDetailsArray[0]['enterprise_id'])) {
                // 判断超售库存
                foreach ($detail_list as $order_cls) {
                    //获取产品详情
                    $product_biz = new \Biz\Product\Product();
                    $product_cls = $product_biz->getProductListById($order_cls->getProductId());
                    foreach ($product_cls->getSkuList() as $k => $skuinfo) {
                        if ($skuinfo->getId() == $order_cls->getProductSkuId()) {
                            $attr = $this->unsertlizeAttr($skuinfo->getAttr());
                        }
                    }
                    //获取产品sku的可用库存
                    $stock_handler = new \Biz\StockHandler();
                    $stock_cls = $stock_handler->loadBySkuIdAndProductId($customer_cls->getWarehouseId(),$order_cls->getProductSkuId(), $order_cls->getProductId());
                    //如果库存表中不存在该条数据，新增一条
                    if (!$stock_cls) {
                        $stock = new \Cls\Warehouse\Stock();
                        $stock->setEnterpriseId($product_cls->getEnterpriseId());
                        $stock->setWarehouseId($customer_cls->getWarehouseId()); //仓库 对应没有sku记录的仓库
                        $stock->setSkuId($order_cls->getProductSkuId());
                        $stock->setProductId($order_cls->getProductId());
                        $stock->setProductName($product_cls->getName());
                        $stock->setProductAttr($attr);
                        $stock->getInsertTime(date('Y-m-d H:i:s', time()));
                        $stock_handler->insert($stock);
                        $stock_cls = $stock_handler->loadBySkuIdAndProductId($customer_cls->getWarehouseId(),$order_cls->getProductSkuId(), $order_cls->getProductId());
                    }

                    //不允许超售的判断库存 && 下单数量大于可用库存
                    if ($product_cls->getOverSale() == 1 && $order_cls->getAmount() > $stock_cls->getAvailableStock()) {
                        return $stock_cls->getProductName() . '属性为' . $stock_cls->getProductAttr() . '的产品库存不足！';
                    }
                }
            }

            //创建订单
            $order_cls = new \Cls\Order\Order();
            $order_cls->create($orderDetailsArray[0]['enterprise_id'], $req['uid'], $orderDetailsArray[0]['channel_id'], $detail_list);

            $order_handler = new \Biz\OrderHandler();
            $order_cls = $order_handler->insert($order_cls);

            if(!is_object($order_cls)) {
                return '订单总额不能小于￥' . $order_cls;
            }
            if($order_cls == 'need_price'){
                return '亲！下单金额不能小于渠道起订金额哦~';
            }
            //拼订单数据
            if ($order_cls instanceof \Cls\Order\Order) {
                //订单SKU详情
                $tmp = $this->pieceOrder($order_cls);
                //时间选择列表
                $channel_biz = new \Biz\ChannelHandler();
                $channel_cls = $channel_biz->getDeliveryByChannelIdAndOrderId($order_cls->getEnterpriseChannelId(),$order_cls->getInsertTime());
                $tmp['dataList'] = $channel_cls;
                //用户信息
                $tmp['userInfo'] = $this->pieceUserInfo($order_cls);
                // 添加支付方式信息
                $pay_type_list = array(
                    array(
                        'type' => '1',
                        'name' => '线上支付',
                        'is_checked' => 1,
                        'items' => array()
                    ),
                    array(
                        'type' => '0',
                        'name' => '线下支付',
                        'is_checked' => 0,
                        'items' => array()
                    )
                );

                $pay_handler = new \Biz\PayHandler();
                $channel_handler = new \Biz\ChannelHandler();
                $channel_cls = $channel_handler::getChannelById($orderDetailsArray[0]['channel_id']);
                $channel_pay = $channel_cls->getChannelPayInfo();
                if($channel_pay){
                    foreach ($channel_pay as $key=>$channel_pay_cls){
                        if($channel_pay_cls->getPayType() == \Cls\Channel\ChannelPay::pay_online_type){
                            $pay_id = $channel_pay_cls->getPayId();
                            $online_pay_list[] = $pay_handler->getByOnlineId($pay_id);
                        }else{
                            $pay_id = $channel_pay_cls->getPayId();
                            $offline_pay_list[] = $pay_handler->getByOfflineId($pay_id);
                        }
                    }
                }
                $online_pay_list = isset($online_pay_list) ? $online_pay_list : array();
                $offline_pay_list = isset($offline_pay_list) ? $offline_pay_list : array();
                foreach ($pay_type_list as $key => $value) {
                    if ($value['type'] == '1') {
                        $pay_type_list[$key]['items'] = $this->pieceOnline($online_pay_list);
                    } else if ($value['type'] == '0') {
                        $pay_type_list[$key]['items'] = $this->pieceOffline($offline_pay_list);
                    }
                }
                $tmp['payTypeList'] = $pay_type_list;

                //增加订单至 solr_order
                $createSolrOrder = $this->createSolrOrderRow($tmp);
                if ($createSolrOrder) {
                    $result = $tmp;
                    return '';
                } else {
                    return 'create solr order error';
                }
            }
            return 'create order filed';

        } catch (\Exception $e) {
            return $e->getMessage();
        }
    }

    public function put(array $req, array $post, &$result)
    {
        try {
            /*if (!array_key_exists('id', $req) || empty($req['id'])) {
                return 'require resource id';
            }*/
            if (!isset($req['uid'])) {
                return 'require user id ';
            }
            if (!isset($req['userType'])) {
                return 'require user type';
            }
            if (!isset($req['k']) || !isset($req['t'])) {
                return 'data error';
            }
            if (!array_key_exists('payload', $post)) {
                return 'require payload';
            }

            $data = base64_decode($post['payload']);
            @parse_str($data, $data);
            if (!array_key_exists('actionType', $data)) {
                return 'essential data required';
            }
            if (!array_key_exists('uid', $data)) {
                return 'essential data required';
            }
            if (!array_key_exists('channelId', $data)) {
                return 'essential data required';
            }

            //PostPay没有资源id
            if ($data['actionType'] != 'postPay') {
                if (!array_key_exists('id', $req) || empty($req['id'])) {
                    return 'require resource id';
                }
                $orderHeader = new \Biz\OrderHandler();
                $order_cls = $orderHeader->getOrderHeadById($req['id']);
                if (!$order_cls instanceof \Cls\Order\Order) {
                    return 'order filed';
                }

                if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $order_cls->getEnterpriseId(), $req['id'] . $req['t'] . $post['payload'], $req['k']) == false) {
                   return 'data illegal';
                }
            } elseif ($data['actionType'] == 'postPay') {
                if (\Biz\UserHandler::checkAuth($req['userType'], $req['uid'], $data['enterpriseId'], $req['t'] . $post['payload'], $req['k']) == false) {
                    return 'data illegal';
                }
            }


            switch ($data['actionType']) {
                case "cancel": //取消订单
                    if (!$order_cls instanceof \Cls\Order\Order) {
                        return 'order error';
                    }
                    //更新t_order
                    $workflowHandler = new \Biz\WorkflowService();
                    $workflowHandler->loadProcess($order_cls->getProcessId());
                    $workflowHandler->overProcess(\Cls\Order\Order::ORDER_STATUS_USER_CANCELED);
                    return '';
                case "submit"://填写地址配送时间这时候订单为新订单1
                    $pay_handler = new \Biz\PayHandler();
                    $isPayType = $data['isPayType']; //支付类型
                    $pay_type_id = isset($data['pay_type_item_id']) ? (int)$data['pay_type_item_id'] : 0;
                    if ($data['isPayType'] == 0) {
                        $offline_pay_cls = $pay_handler->getOfflineByEnterpriseId($order_cls->getEnterpriseId(), $pay_type_id);
                        if (empty($offline_pay_cls)) {
                            return '商家暂未设置线下支付';
                        }
                    } else if ($data['isPayType'] == 1) {
                        $online_pay_cls = $pay_handler->getOnlineByEnterpriseId($order_cls->getEnterpriseId(), $pay_type_id);
                        if (empty($online_pay_cls)) {
                            return '商家暂未设置线上支付';
                        }
                    } else {
                        return '商家暂未设置具体支付方式';
                    }
                    $order_cls->setPayTypeItemId($pay_type_id);
                    $order_cls->setDeliveryTime($data['deliveryTime']);
                    $order_cls->setContact($data['contact']);
                    $order_cls->setTelephone($data['tel']);
                    $order_cls->setDeliveryAddress($data['address']);
                    $order_cls->setRemark($data['remark']);
                    $order_cls->setStatus(\Cls\Order\Order::ORDER_STATUS_NEW);
                    $order_cls->setIsPayType($isPayType);
                    $result = $orderHeader->update($order_cls);
                    if (!$result) {
                        return 'modfily failed';
                    }
                    //更新solr
                    $solr_handler = new \Biz\Solr\OrderBiz();
                    $solr_handler->updateSolrOrder();

                    $workflowHandler = new \Biz\WorkflowService();
                    $workflowHandler->initProcess($order_cls->getEnterpriseId(), \Cls\Workflow\Workflow::WORKFLOW_ORDER, $req['id']);
                    $rs = $workflowHandler->run();
                    if (!$rs['isok']) {
                        return $rs['msg'];
                    }
                    /*返回订单详情信息*/
                    $order_cls = $orderHeader->getOrderAndDetailByOrderId($req['id']);
                    //添加客户名称
                    $orderHeader = $this->orderFiled($order_cls);
                    $result = $orderHeader ? $orderHeader : array();
                    return '';
                case "postPay"://APP 同步执行的方法
                    if (!array_key_exists('platform', $data) || !array_key_exists('outTradeNo', $data)) {
                        return 'essential data required';
                    }
                    if ($data['platform'] == 'ZFB') {//支付宝支付岁
                        $data = $this->PostPay($data, $req['id'], $req['uid'], $data['platform']);
                        if ($data['result'] == 'OK') {
                            $result = $data['data'];
                        }
                        return '';
                    } elseif ($data['platform'] == 'WX') {//微信支付
                        $data = $this->PostPay($data, $req['id'], $req['uid'], $data['platform']);
                        if ($data['result'] == 'OK') {
                            $result = $data['data'];
                        }
                    } elseif ($data == 'OFFLINE') {
                    } else {
                    }
                    break;
                case "prePay"://支付
                    //创建交易流水号返回签名
                    if (!array_key_exists('enterpriseId', $data)) return 'require enterpriseId';
                    if (!array_key_exists('platform', $data)) return 'require platform';
                    //1查询该订单是否有未完成的transaction 交易流水号
                    $transcation_handler = new \Biz\TransactionHandler();
                    $tabulation = new \Cls\Tabulation();
                    $tabulation->setWhere('reference', $req['id']);
                    $tabulation->setWhere('platform', $data['platform']);
                    $tabulation->setWhere('status', \Cls\Transaction\Transaction::NEW_TRANSACTION_STATUS);
                    $tabulation->setWhere('type', 1);
                    $transcation_handler->getTransactionByOrderId($tabulation);
                    $transcation_item = $tabulation->getData();
                    $transcation_cls = reset($transcation_item);

                    if ($transcation_cls instanceof \Cls\Transaction\Transaction) {
                        $Transaction = $this->piceTranscation($transcation_cls);
                    } else {
                        $transaction_handler = new \Biz\transactionHandler();
                        $transaction_cls = new \Cls\Transaction\Transaction();
                        $order_id = $req['id'];
                        $customer_id = $req['uid'];
                        $enterprise_id = $data['enterpriseId'];
                        $order_need_pay_price = $order_cls->getNeedPayPrice();
                        $type = \Cls\Transaction\Transaction::TRANSACTION_TYPE_CUSTOMER_ORDER;
                        $status = \Cls\Transaction\Transaction::NEW_TRANSACTION_STATUS;
                        $platform = $data['platform'];
                        $transaction_cls->create($order_id, $customer_id, $enterprise_id, $order_need_pay_price, $type, $status, $platform);
                        $create_tranaction = $transaction_handler->insert($transaction_cls);
                        if (!$create_tranaction instanceof \Cls\Transaction\Transaction) {
                            return 'create transcation filed';
                        }
                        $Transaction = $this->piceTranscation($create_tranaction);
                    }
                    //2 第三方平台调用
                    if ($data['platform'] == 'ZFB') {
                        //支付宝支付
                        $data = $this->AliPay($data, $req['id'], $req['uid'], $Transaction);
                        if ($data['result'] == 'OK') {
                            $result = $data['data'];
                        } else {
                            return $data['msg'];
                        }
                    } else if ($data['platform'] == 'WX') {
                        $data = $this->Wxpay($data, $req['open_id'], $req['id'], $req['uid'], $Transaction);
                        if ($data['result'] == 'OK') {
                            $result = $data['data'];
                        } else {
                            return $data['msg'];
                        }
                    } else if ($data['platform'] == 'OFFLINE') {
                    } else {
                    }
                    break;
                case "OfflinePay"://支付
                    //创建交易流水号返回签名
                    if (isset($data['offline_pay_item_id']) == false) {
                        return 'required offline item id ';
                    }

                    $order_handler = new \Biz\OrderHandler();
                    $order_cls = $order_handler->getOrderHeadById($req['id']);
                    $order_cls->setPayClassType('线下支付');
                    //$order_cls->setPayStatus(\Cls\Order\Order::PAY_STATUS_HAD);
                    $order_cls->setIsPayType(\Cls\Order\Order::IS_PAY_TYPE_OFFLINE);
                    $order_cls->setPayTypeItemId($data['offline_pay_item_id']);
                    $updateOrder = $orderHeader->update($order_cls);
                    if (!$updateOrder) {
                        return 'modfily failed';
                    }
                    break;
                default:
                    return 'unkown options';
            }
        } catch (Exception $e) {
            return $e->getMessage();
        }
    }

    //返回微信支付签名
    private function Wxpay($data, $open_id, $orderId, $userId, $Transaction)
    {
        $msgData = array('msg' => '', 'result' => 'NO', 'data' => null);
        if (empty($data) || empty($orderId) || empty($userId) || empty($Transaction)) {
            $msgData['msg'] = '参数有误';
            return $msgData;
        }
        //订单详情
        $order_handler = new \Biz\OrderHandler();
        $tabulation_order = new \Cls\Tabulation();
        $tabulation_order->setWhere('id', $orderId);
        $tabulation_order->setWhere('pay_status', \Cls\Order\Order::PAY_STATUS_NOT);
        $tabulation_order->setWhere('status', \Cls\Order\Order::ORDER_STATUS_NEW);
        $order_handler->getOrderListByEnterpriseId($tabulation_order);
        $order_items = $tabulation_order->getData();
        $order_cls = reset($order_items);
        if (!$order_cls instanceof \Cls\Order\Order) {
            $msgData['msg'] = '未查询到有效的订单';
            return $msgData;
        }
        //查询该交易流水号是否可用
        $outTradeNo = $Transaction['out_trade_no'];
        $wxPayConfig = \WxPay::getPayConfig($order_cls->getEnterpriseId());
        $checkOrder = \WxPay::checkOrderQuery($wxPayConfig, $outTradeNo);
        $orderData['ordercode'] = $order_cls->getCode();
        $orderData['need_pay_price'] = $order_cls->getNeedPayPrice();
        $orderData['id'] = $order_cls->getId();
        $orderData['channel_discount'] = $order_cls->getChannelDiscount();
        $orderData['insert_time'] = $order_cls->getInsertTime();
        if ($checkOrder == 'CHECK_FAILED') { //微信算签名
            //获取微信配置
            $WxPaysign = \WxPay::getPreSign($wxPayConfig, $orderData, $Transaction, $open_id);
            $msgData['result'] = 'OK';
            $msgData['data'] = array('rsa' => $WxPaysign, 'out_trade_no' => $Transaction['out_trade_no']);//返回微信支付签名，流水号
            return $msgData;
        }
        $transcation_handler = new \Biz\TransactionHandler();
        $tabulation = new \Cls\Tabulation();
        $tabulation->setWhere('id', $Transaction['id']);
        $tabulation->setWhere('reference', $orderId);
        $tabulation->setWhere('status', \Cls\Transaction\Transaction::NEW_TRANSACTION_STATUS);
        $transcation_handler->getTransactionByOrderId($tabulation);
        $transcation_item = $tabulation->getData();
        $transcation_cls = reset($transcation_item);
        if ($transcation_cls instanceof \Cls\Transaction\Transaction) {
            $transcation_cls->setStatus(\Cls\Transaction\Transaction::NO_TRANSACTION_STATUS);
            $transcation_handler->update($transcation_cls);
        }

        $msgData['msg'] = 'AGAIN_PRE_PAY';
//        $editTransaction = \TransactionModel::updateTransaction(
//            array('id' => $Transaction['id'], 'reference' => $orderId, 'status' => \TransactionModel::NEW_TRANSACTION_STATUS),
//            array('status' => \TransactionModel::NO_TRANSACTION_STATUS,)
//        );
//        $msgData['msg'] = 'AGAIN_PRE_PAY';
        return $msgData;
    }

    /**
     * 支付宝支付签名生成
     * @param $data
     * @param $orderId
     * @param $userId
     * @param $Transaction
     * @return array
     */
    private function AliPay($data, $orderId, $userId, $Transaction)
    {//'5001000100010001910'
        $msgData = array('msg' => '', 'result' => 'NO', 'data' => null);
        //订单详情
        $order_handler = new \Biz\OrderHandler();
        $tabulation_order = new \Cls\Tabulation();
        $tabulation_order->setWhere('id', $orderId);
        $tabulation_order->setWhere('pay_status', \Cls\Order\Order::PAY_STATUS_NOT);
        $tabulation_order->setWhere('status', \Cls\Order\Order::ORDER_STATUS_NEW);
        $order_handler->getOrderListByEnterpriseId($tabulation_order);
        $order_items = $tabulation_order->getData();
        $order_cls = reset($order_items);
        if (!$order_cls instanceof \Cls\Order\Order) {
            $msgData['msg'] = '未查询到有效的订单';
            return $msgData;
        }

        //查询该交易流水号是否可用
        $outTradeNo = $Transaction['out_trade_no'];
        $checkOrder = \AliPayConfig::ZFBorderQuery($outTradeNo, $data['enterpriseId']);
        if (is_numeric($checkOrder) && strlen($checkOrder) >= 16) {
            //将本地的流水也改为不可用
            $transcation_handler = new \Biz\TransactionHandler();
            $tabulation = new \Cls\Tabulation();
            $tabulation->setWhere('id', $Transaction['id']);
            $tabulation->setWhere('reference', $orderId);
            $tabulation->setWhere('status', \Cls\Transaction\Transaction::NEW_TRANSACTION_STATUS);
            $transcation_handler->getTransactionByOrderId($tabulation);
            $transcation_item = $tabulation->getData();
            $transcation_cls = reset($transcation_item);
            if ($transcation_cls instanceof \Cls\Transaction\Transaction) {
                $transcation_cls->setStatus(\Cls\Transaction\Transaction::NO_TRANSACTION_STATUS);
                $transcation_handler->update($transcation_cls);
            }
            $msgData['msg'] = '该交易号已经被使用';
            return $msgData;
        }

        if (($checkOrder == 'PAY_FAILED') || ($checkOrder == 'PAY_FAILED')) {
            $transcation_handler = new \Biz\TransactionHandler();
            $tabulation = new \Cls\Tabulation();
            $tabulation->setWhere('id', $Transaction['id']);
            $tabulation->setWhere('reference', $orderId);
            $tabulation->setWhere('status', \Cls\Transaction\Transaction::NEW_TRANSACTION_STATUS);
            $transcation_handler->getTransactionByOrderId($tabulation);
            $transcation_item = $tabulation->getData();
            $transcation_cls = reset($transcation_item);
            if ($transcation_cls instanceof \Cls\Transaction\Transaction) {
                $transcation_cls->setStatus(\Cls\Transaction\Transaction::NO_TRANSACTION_STATUS);
                $transcation_handler->update($transcation_cls);
            }
            $msgData['msg'] = '该交易号已经被使用';
            return $msgData;
        }////调用修改订单，Transaction 的方法 修改为失败
        if ($checkOrder == 'PAY_WAIT') {
            $transcation_handler = new \Biz\TransactionHandler();
            $tabulation = new \Cls\Tabulation();
            $tabulation->setWhere('id', $Transaction['id']);
            $tabulation->setWhere('reference', $orderId);
            $tabulation->setWhere('status', \Cls\Transaction\Transaction::NEW_TRANSACTION_STATUS);
            $transcation_handler->getTransactionByOrderId($tabulation);
            $transcation_item = $tabulation->getData();
            $transcation_cls = reset($transcation_item);
            if ($transcation_cls instanceof \Cls\Transaction\Transaction) {
                $transcation_cls->setStatus(\Cls\Transaction\Transaction::NO_TRANSACTION_STATUS);
                $transcation_handler->update($transcation_cls);
            }
            $msgData['msg'] = 'AGAIN_PRE_PAY';
            return $msgData;
        }
        //生成app支付签名1.获取app签名配置
        $alipayItems = \AliPayConfig::getConfig($data['enterpriseId'], 'ZFB');
        if (!$alipayItems) {
            $msgData['msg'] = '支付配置信息错误';
            return $msgData;
        }
        $sendDatas = array(
            'partner' => $alipayItems['pay_config']['partner_id'],//合作者ID
            'seller_id' => $alipayItems['pay_config']['enterprise_alipay_account'],//支付宝企业账号
            'out_trade_no' => $Transaction['out_trade_no'],//$alipayItems['id'],//订单号
            'subject' => '订单号:' . $order_cls->getCode(),
            'body' => '',//产品描述
            'total_fee' => $order_cls->getNeedPayPrice(),//产品价格
            //'total_fee' => '0.01',// 测试价格为1分钱
            'notify_url' => 'http://' . $_SERVER['HTTP_HOST'] . '/PayCallback',//回调地址
            'service' => 'mobile.securitypay.pay',//系统参数
            'payment_type' => 1,//支付类型
            '_input_charset' => 'utf-8',
            'it_b_pay' => '30m',
            'show_url' => 'm.alipay.com',
        );
        $sign = \AliPayConfig::getMySin($sendDatas, $alipayItems['pay_config']['private_pkcs8rsa_key']);
        $data = array(
            'rsa' => \AliPayConfig::createLinkstring($sendDatas) . '&sign="' . $sign . '"&sign_type="' . \AliPayConfig::SIGN_TYPE . '"',
            'out_trade_no' => $Transaction['out_trade_no'],
        );
        $msgData['result'] = 'OK';
        $msgData['data'] = $data;
        return $msgData;
    }

    /*
     * APP 同步执行的方法
     * @param $data
     * @param $orderId
     * @param $userId
     */
    private function PostPay($data, $orderId, $userId, $platform)
    {
        $msgData = array('msg' => '', 'result' => 'NO', 'data' => null);
        //首先验证 transaction
        $transaction_handler = new \Biz\TransactionHandler();
        $tabulation = new \Cls\Tabulation();
        $tabulation->setWhere('platform', $platform);
        $tabulation->setWhere('reference', $orderId);
        $tabulation->setWhere('status', \Cls\Transaction\Transaction::NEW_TRANSACTION_STATUS);
        $tabulation->setWhere('out_trade_no', $data['outTradeNo']);
        $tabulation->setLimit('1');
        $transaction_handler->getTransactionByOrderId($tabulation);
        $transaction_item = $tabulation->getData();
        $transaction_cls = reset($transaction_item);
        //查询支付宝订单的状态
        if (!$transaction_cls instanceof \Cls\Transaction\Transaction) {
            $msgData['msg'] = '没有查询到相关订单交易号';
            return $msgData;
        }
        //'2016072021001004910283167622';支付
        if ($platform == 'ZFB') {
            $pay_class_type = '支付宝支付';
            $querOrder = \AliPayConfig::ZFBorderQuery($transaction_cls->getOutTradeNo(), $data['enterpriseId']);
        } elseif ($platform == 'WX') {
            $pay_class_type = '微信支付';
            $WxPayItems = \WxPay::getPayConfig($data['enterpriseId']);
            $querOrder = \WxPay::checkOrderQuery($WxPayItems, $transaction_cls->getOutTradeNo());
        } else {
            $querOrder = '';
        }

        if (is_numeric($querOrder) && strlen($querOrder) >= 10) {
            //支付成功 修改transaction 订单的状态
            $tabulation_cls = new \Cls\Tabulation();
            $tabulation_cls->setWhere('id', $transaction_cls->getId());
            $tabulation_cls->setWhere('reference', $transaction_cls->getReference());
            $tabulation_cls->setWhere('out_trade_no', $transaction_cls->getOutTradeNo());
            $tabulation_cls->setWhere('status', $transaction_cls->getStatus());
            $transaction_handler->getTransactionByOrderId($tabulation_cls);
            $transaction_item = $tabulation_cls->getData();
            $transaction_cls = reset($transaction_item);
            if (!$transaction_cls instanceof \Cls\Transaction\Transaction) {
                $msgData['msg'] = '没有查询到相关流水交易号';
                return $msgData;
            }
            $transaction_cls->setStatus(\Cls\Transaction\Transaction::OK_TRANSACTION_STATUS);
            $transaction_cls->setPlatformId($querOrder);
            $editTransaction = $transaction_handler->update($transaction_cls);
            if ($editTransaction) {
                //修改订单
                $order_handler = new \Biz\OrderHandler();
                $tabulation_edit_cls = new \Cls\Tabulation();
                $tabulation_edit_cls->setWhere('id', $orderId);
                $tabulation_edit_cls->setWhere('enterprise_id', $data['enterpriseId']);
                $tabulation_edit_cls->setWhere('enterprise_customer_id', $userId);
                $tabulation_edit_cls->setWhere('status', \Cls\Order\Order::ORDER_STATUS_NEW);
                $tabulation_edit_cls->setWhere('pay_status', \Cls\Order\Order::PAY_STATUS_NOT);
                $order_handler->getOrderListByEnterpriseId($tabulation_edit_cls);
                $order_edit_item = $tabulation_edit_cls->getData();
                $order_edit_cls = reset($order_edit_item);
                if (!$order_edit_cls instanceof \Cls\Order\Order) {
                    $msgData['msg'] = '没有查询到相关订单';
                    return $msgData;
                }
                $order_edit_cls->setTransactionId($transaction_cls->getId());
                $order_edit_cls->setPayTime(date('Y-m-d H:i:s'));
                $order_edit_cls->setIsPayType('1');
                $order_edit_cls->setPayStatus(\Cls\Order\Order::PAY_STATUS_HAD);
                $order_edit_cls->setPayClassType($pay_class_type);
                //更新t_order
                $editOrder = $order_handler->update($order_edit_cls);
                //更新solr
                $solr_handler = new \Biz\Solr\OrderBiz();
                $solr_handler->updateSolrOrder();
                if ($editOrder) {
                    $msgData['result'] = 'OK';
                    $msgData['data'] = '更新成功';
                    return $msgData;
                }
            }
        } else {
            $msgData['result'] = 'NO';
            $msgData['msg'] = '没有查询到相关交易号订单';
            return $msgData;
        }
        return array();
    }

    private function orderFiled(\Cls\Order\Order $order_cls, $is_sku = 0)
    {
        $orderHeader = array();
        $orderBody = array();
        if($order_cls->getIsPayType()==\Cls\Order\Order::IS_PAY_TYPE_OFFLINE){
            $pay_type = '线下支付';
        }else{
            $pay_type = '线上支付';
        }
        $orderHeader['id'] = $order_cls->getId();
        $orderHeader['ordercode'] = $order_cls->getCode();
        $orderHeader['enterprise_id'] = $order_cls->getEnterpriseId();
        $orderHeader['enterprise_customer_id'] = $order_cls->getEnterpriseCustomerId();
        $orderHeader['enterprise_channel_id'] = $order_cls->getEnterpriseChannelId();
        $orderHeader['status'] = $order_cls->getStatus();
        $orderHeader['contact'] = $order_cls->getContact();
        $orderHeader['tel'] = $order_cls->getTelephone();
        $orderHeader['price'] = $order_cls->getPrice();
        $orderHeader['discount'] = $order_cls->getDiscount();
        $orderHeader['coupon'] = $order_cls->getConupon();
        $orderHeader['need_pay_price'] = $order_cls->getNeedPayPrice();
        $orderHeader['pay_status'] = $order_cls->getPayStatus();
        $orderHeader['pay_datetime'] = $order_cls->getPayTime();
        $orderHeader['pay_message'] = $order_cls->getPayMessage();
        $orderHeader['delivery_status'] = $order_cls->getDeliveryStatus();
        $orderHeader['delivery_charge'] = $order_cls->getDeliveryCharge();
        $orderHeader['delivery_time'] = $order_cls->getDeliveryTime();
        $orderHeader['delivery_province_id'] = $order_cls->getDeliveryProvinceId();
        $orderHeader['delivery_city_id'] = $order_cls->getDeliveryCityId();
        $orderHeader['delivery_address'] = $order_cls->getDeliveryAddress();
        $orderHeader['remark'] = $order_cls->getRemark();
        $orderHeader['active_discount'] = $order_cls->getActiveDiscount();
        $orderHeader['insert_time'] = $order_cls->getInsertTime();
        $orderHeader['update_time'] = $order_cls->getUpdateTime();
        $orderHeader['is_pay_type'] = $order_cls->getIsPayType();
        $orderHeader['pay_type_item_id'] = $order_cls->getPayTypeItemId();
        $orderHeader['transaction_id'] = $order_cls->getTransactionId();
        $orderHeader['status_string'] = $order_cls->getStatusStr();
        $orderHeader['pay_status_string'] = $order_cls->getPayStatusStr();
        $orderHeader['delivery_status_string'] = $order_cls->getDeliveryStatusStr();
        $orderHeader['pay_class_type'] = $pay_type;

        $channel_cls = $order_cls->getEnterpriseChannelInfo();
        $orderHeader['channel_name'] = $channel_cls->getName();
        $customer_cls = $order_cls->getEnterpriseCustomerInfo();
        $orderHeader['customer_name'] = $customer_cls->getContact();
        $orderHeader['customer_company'] = $customer_cls->getCompany();
        $orderHeader['customer_tel'] = $customer_cls->getTelephone();

        //获取支付信息
        $pay_handler = new \Biz\PayHandler();
        $pay_item_id = $order_cls->getPayTypeItemId();
        if ($order_cls->getIsPayType() == 1) {         //线上支付
            $online_pay_cls = $pay_handler->getByOnlineId($pay_item_id);
            $orderHeader['pay_class_code'] = $online_pay_cls->getCode();
            $orderHeader['type'] = $online_pay_cls->getPayTypeName();
            $orderHeader['bank_number'] = '';
            $orderHeader['bank_account'] = '';
        } elseif ($order_cls->getIsPayType() == 0) {  //线下支付
            $orderHeader['pay_class_code'] = '';
            $offline_pay_cls = $pay_handler->getByOfflineId($pay_item_id);
            if (is_object($offline_pay_cls)) {
                $orderHeader['customer_name'] = $offline_pay_cls->getContact();
                $orderHeader['bank_number'] = $offline_pay_cls->getBankNumber();
                $orderHeader['account'] = $offline_pay_cls->getAccount();
                $orderHeader['bank_name'] = $offline_pay_cls->getBankName();
            }
            $orderHeader['type'] = '线下支付';
        }
        $skuList = $order_cls->getDetailList();
        if ($skuList) {
            $orderBody=array();
            /**
             * @var \Cls\Order\Detail $sku_cls
             */
            foreach ($skuList as $k => $sku_cls) {
                if (is_object($sku_cls)) {
                    $inco_url = $skuList['product_list'][$sku_cls->getProductId()]->dealIconUrl() ? $skuList['product_list'][$sku_cls->getProductId()]->dealIconUrl() : '';
                    $temp = array();
                    $temp['id'] = $sku_cls->getId();
                    $temp['order_id'] = $sku_cls->getOrderId();
                    $temp['product_id'] = $sku_cls->getProductId();
                    $temp['product_name'] = $sku_cls->getProductName();
                    $temp['product_sku_id'] = $sku_cls->getProductSkuId();
                    $temp['product_sku_attr'] = $sku_cls->getProductSkuAttr();
                    $temp['individual_packing'] = $sku_cls->getSellUnitString(); // 老版本
                    $temp['mass_packing'] = $sku_cls->getSellUnitString(); // 老版本
                    $temp['sell_unit_string'] = $sku_cls->getSellUnitString();
                    $temp['active_condition'] = $sku_cls->getActiveCondition();
                    $temp['active_num'] = $sku_cls->getActiveNum();
                    $temp['active_discount'] = $sku_cls->getActiveDiscount();
                    $temp['cost'] = $sku_cls->getCost();
                    $temp['price'] = $sku_cls->getPrice();
                    $temp['amount'] = $sku_cls->getAmount();
                    $temp['repertory_sum'] = $sku_cls->getRepertorySum();
                    $temp['total'] = $sku_cls->getTotal();
                    $temp['is_active'] = $sku_cls->getActiveStatus();
                    $temp['img'] = $inco_url;
                    $orderBody[] = $temp;
                }
            }
        }

        if ($is_sku == 1) {
            return array('orderHeader' => $orderHeader, 'orderBody' => $orderBody);
        } else {
            return array('orderHeader' => $orderHeader,);
        }
    }


    //创建solor订单
    private function createSolrOrderRow($tmpOrder)
    {
        if (empty($tmpOrder)) return false;
        $oH = $tmpOrder['orderHeader'];
        $oB = $tmpOrder['orderBody'];
        $u = $tmpOrder['userInfo'];
        $product_ids = self::getProducts($oB, 'id') ? self::getProducts($oB, 'id') : '';
        $product_names = self::getProducts($oB, 'product_names') ? self::getProducts($oB, 'product_names') : '';
        $channel_handler = new \Biz\ChannelHandler();
        $channel_cls = $channel_handler->getChannelById($oH['enterprise_channel_id']);
        $solr_order_cls = new \Cls\Order\SolrOrder();
        $solr_order_cls->setOrderId($oH['id']);
        $solr_order_cls->setOrderCode($oH['ordercode']);
        $solr_order_cls->setStatus($oH['status']);
        $solr_order_cls->setPayStatus($oH['pay_status']);
        $solr_order_cls->setDeliveryStatus($oH['delivery_status']);
        $solr_order_cls->setCustomerId($u['id']);
        $solr_order_cls->setCustomerAccount($u['company']);
        $solr_order_cls->setCustomerCode($u['customer_code']);
        $solr_order_cls->setEnterpriseId($oH['enterprise_id']);
        $solr_order_cls->setEnterpriseChannelId($oH['enterprise_channel_id']);
        $solr_order_cls->setEnterpriseChannelName($channel_cls->getName());
        $solr_order_cls->setProductIds($product_ids);
        $solr_order_cls->setProductNames($product_names);
        $solr_order_cls->setNeedPayPrice($oH['need_pay_price']);
        $solr_order_cls->setCreateTime(date('YmdHis', strtotime($oH['insert_time'])));

        $solr_order = new \Biz\Solr\OrderBiz();
        $res = $solr_order->insert($solr_order_cls);
        if ($res) {
            return $res;
        } else {
            return false;
        }
    }

    private static function getProducts($items, $type = 'id')
    {
        if (empty($items)) return false;
        $items = json_decode(json_encode($items), true);
        $tmp = array();
        if ($type == 'id') {
            $vk = 'product_id';
        } else if ($type == 'product_names') {
            $vk = 'product_name';
        } else {
            $vk = 'product_id';
        }
        foreach ($items as $k => $v) {
            array_push($tmp, $v[$vk]);
        }
        if ($tmp) {
            return implode(',', $tmp);
        }
        return $tmp;
    }

    private static function getDateList()
    {
        $Date1 = date('Y-m-d H:i', time() + 24 * 3600); /*格式   年-月-日 或 年-月-日 时:分:秒*/
        $Date2 = date("Y-m-d H:i", strtotime($Date1) + (24 * 3600 * 10));
        $tmp = array();
        for ($i = strtotime($Date1); $i <= strtotime($Date2); $i += 86400) {
            $ThisDate = date("Y-m-d H:i:s", $i);
            array_push($tmp, $ThisDate);
        }
        return $tmp;
    }


    /**订单享受渠道折扣
     * @param $tmp
     * @param $discount
     * @return string
     */
    public function channelDiscount($tmp, $discount)
    {
        // 修改订单产品价格
        foreach ($tmp['orderBody'] as $k => $product) {
            $order_detail_handler = new \Biz\OrderDetailHandler();
            $order_detail_cls = $order_detail_handler->getOrderDetailByid($product['id']);
            if ($order_detail_cls instanceof \Cls\Order\Detail) {
                $total = round(($product['total'] * $discount), 2);
                $order_detail_cls->setTotal($total);
            }
            $order_detail_handler->update($order_detail_cls);
        }
        //修改订单中的总价
        $orderHeader = new \Biz\OrderHandler();
        $order_cls = $orderHeader->getOrderHeadById($tmp['orderHeader']['id']);
        $orderbody = $this->objtoarr($tmp['orderBody']);
        $total = array_sum($this->low_array_column($orderbody, 'total'));
        $tmp['orderHeader']['need_pay_price'] = $total;
        $order_cls->setNeedPayPrice($total);
        $res = $orderHeader->update($order_cls);
        if (!$res) {
            return 'Failed to participate in activities!';
        }
        return $tmp;
    }

    private function objtoarr($obj)
    {
        $ret = array();
        foreach ($obj as $key => $value) {
            if (gettype($value) == 'array' || gettype($value) == 'object') {
                $ret[$key] = $this->objtoarr($value);
            } else {
                $ret[$key] = $value;
            }
        }
        return $ret;
    }

    /**
     * orderList = productId;num;cid; eid;skuId,productId;num;cid;eid;skuId
     * 订单参数列    产品id    数量 渠道id 企业ID skuid ,产品id   数量 渠道id 企业id skuid
     * @param $string
     * @return array
     */
    private static function order_product_array($string)
    {
        if (empty($string)) return false;
        $toListArray = explode(',', $string);
        $tmpOrderProductArray = array();
        foreach ($toListArray as $k => $v) {
            $tmp = array();
            $productList = explode(';', $v);
            $tmp['product_id'] = $productList[0];
            $tmp['product_num'] = $productList[1];
            $tmp['channel_id'] = $productList[2];
            $tmp['enterprise_id'] = $productList[3];
            $tmp['sku_id'] = $productList[4];
            $tmpOrderProductArray[] = $tmp;
        }
        if ($tmpOrderProductArray) return $tmpOrderProductArray;
        return false;
    }

    /*
     * 拼凑订单头
     * @param  Cls\Order\Order  $order_cls
     */
    private function pieceOrder(\Cls\Order\Order $order_cls)
    {
        $orderHeader = array();
        $orderBody = array();
        if($order_cls->getIsPayType()==\Cls\Order\Order::IS_PAY_TYPE_OFFLINE){
            $pay_type = '线下支付';
        }else{
            $pay_type = '线上支付';
        }
        $orderHeader['id'] = $order_cls->getId();
        $orderHeader['ordercode'] = $order_cls->getCode();
        $orderHeader['enterprise_id'] = (string)$order_cls->getEnterpriseId();
        $orderHeader['enterprise_customer_id'] = (string)$order_cls->getEnterpriseCustomerId();
        $orderHeader['enterprise_channel_id'] = (string)$order_cls->getEnterpriseChannelId();
        $orderHeader['status'] = (string)$order_cls->getStatus();
        $orderHeader['contact'] = (string)$order_cls->getContact();
        $orderHeader['tel'] = (string)$order_cls->getTelephone();
        $orderHeader['price'] = (string)$order_cls->getPrice();
        $orderHeader['discount'] = (string)$order_cls->getDiscount();
        $orderHeader['coupon'] = (string)$order_cls->getConupon();
        $orderHeader['need_pay_price'] = (string)$order_cls->getNeedPayPrice();
        $orderHeader['pay_status'] = (string)$order_cls->getPayStatus();
        $orderHeader['pay_datetime'] = (string)$order_cls->getPayTime();
        $orderHeader['pay_message'] = (string)$order_cls->getPayMessage();
        $orderHeader['delivery_status'] = (string)$order_cls->getDeliveryStatus();
        $orderHeader['delivery_charge'] = (string)$order_cls->getDeliveryCharge();
        $orderHeader['delivery_time'] = (string)$order_cls->getDeliveryTime();
        $orderHeader['delivery_province_id'] = (string)$order_cls->getDeliveryProvinceId();
        $orderHeader['delivery_city_id'] = (string)$order_cls->getDeliveryCityId();
        $orderHeader['delivery_address'] = (string)$order_cls->getDeliveryAddress();
        $orderHeader['remark'] = (string)$order_cls->getRemark();
        $orderHeader['active_discount'] = (string)$order_cls->getActiveDiscount();
        $orderHeader['insert_time'] = (string)$order_cls->getInsertTime();
        $orderHeader['update_time'] = (string)$order_cls->getUpdateTime();
        $orderHeader['is_pay_type'] = (string)$order_cls->getIsPayType();
        $orderHeader['pay_type_item_id'] = $order_cls->getPayTypeItemId() ? (string)$order_cls->getPayTypeItemId() : '';
        $orderHeader['transaction_id'] = (string)$order_cls->getTransactionId();
        $orderHeader['is_del'] = '0';
        $orderHeader['pay_class_type'] = $pay_type ? (string)$pay_type : '';
        $skuList = $order_cls->getDetailList();
        if ($skuList) {
            foreach ($skuList as $k => $sku_cls) {
                if (is_object($sku_cls)) {
                    $inco_url = $skuList['product_list'][$sku_cls->getProductId()]->dealIconUrl() ? $skuList['product_list'][$sku_cls->getProductId()]->dealIconUrl() : '';
                    $temp = array();
                    $temp['id'] = (string)$sku_cls->getId();
                    $temp['order_id'] = (string)$sku_cls->getOrderId();
                    $temp['product_id'] = (string)$sku_cls->getProductId();
                    $temp['product_name'] = (string)$sku_cls->getProductName();
                    $temp['product_sku_id'] = (string)$sku_cls->getProductSkuId();
                    $temp['product_sku_attr'] = (string)$sku_cls->getProductSkuAttr();
                    $temp['individual_packing'] = (string)$sku_cls->getSellUnitString(); // 老版本
                    $temp['mass_packing'] = (string)$sku_cls->getSellUnitString(); // 老版本
                    $temp['sell_unit_string'] = (string)$sku_cls->getSellUnitString();
                    $temp['active_condition'] = (string)$sku_cls->getActiveCondition();
                    $temp['active_num'] = (string)$sku_cls->getActiveNum();
                    $temp['active_discount'] = (string)$sku_cls->getActiveDiscount();
                    $temp['cost'] = (string)$sku_cls->getCost();
                    $temp['price'] = (string)$sku_cls->getPrice();
                    $temp['amount'] = (string)$sku_cls->getAmount();
                    $temp['repertory_sum'] = (string)$sku_cls->getRepertorySum();
                    $temp['total'] = (string)$sku_cls->getTotal();
                    $temp['is_active'] = (string)$sku_cls->getActiveStatus();
                    $temp['img'] = $inco_url;
                    $orderBody[] = $temp;
                }
            }
        }

        return array('orderHeader' => $orderHeader, 'orderBody' => $orderBody);
    }

    /*
     * 拼凑用户信息
     * @param  Cls\Order\Order  $order_cls
     */
    private function pieceUserInfo(\Cls\Order\Order $order_cls)
    {
        $userInfo = array();
        $user = $order_cls->getEnterpriseCustomerInfo();
        $region = $user->getRegion();

        $userInfo['id'] = (string)$user->getId();
        $userInfo['account'] = (string)$user->getAccount();
        $userInfo['pwd'] = (string)$user->getPassword();
        //$userInfo['name']               = $user->getName();
        //$userInfo['qq']                 = $user->getQQ();
        $userInfo['company'] = (string)$user->getCompany();
        $userInfo['contact'] = (string)$user->getContact();
        $userInfo['admin_id'] = (string)$user->getAdminId();
        //$userInfo['department']         = $user->getDepartment();
        $userInfo['customer_code'] = (string)$user->getCustomerCode();
        $userInfo['tel'] = (string)$user->getTelephone();
        $userInfo['channel_id'] = (string)$user->getChannelId();
        $userInfo['enterprise_id'] = (string)$user->getEnterpriseId();
        //$userInfo['enterprise_role_id'] = $user->getEnterpriseRoleId();
        $userInfo['warehouse_id'] = (string)$user->getWarehouseId();
        $userInfo['country'] = (string)$region->getCountryId();
        $userInfo['countryname'] = (string)$region->getCountryName();
        $userInfo['province'] = (string)$region->getProvinceId();
        $userInfo['provincename'] = (string)$region->getProvinceName();
        $userInfo['city'] = (string)$region->getCityId();
        $userInfo['cityname'] = (string)$region->getCityName();
        $userInfo['area'] = (string)$region->getAreaId();
        $userInfo['areaname'] = (string)$region->getAreaName();
        $userInfo['address'] = (string)$region->getAddress();
        //$userInfo['email']              = $user->getEmail();
        //$userInfo['type']               = (string)$user->getType();
        $userInfo['remark'] = (string)$user->getRemark();
        $userInfo['is_del'] = (string)$user->getDelStatus();
        //$userInfo['is_use']             = (string)$user->getUseStatus();
        $userInfo['insert_time'] = (string)$user->getCreateTime();
        $userInfo['update_time'] = (string)$user->getUpdateTime();

        return $userInfo;
    }

    /*
     * 拼凑活动信息
     * @param  Cls\Market\Market  $market_cls
     */
    private function pieceActivity(\Cls\Market\Market $market_cls)
    {
        $activity = array();
        $activity['id'] = (string)$market_cls->getId();
        $activity['title'] = (string)$market_cls->getTitle();
        $activity['type'] = (string)$market_cls->getType();
        $activity['condition'] = $market_cls->getCondition() ? (string)$market_cls->getCondition() : '0';
        $activity['discount'] = (string)$market_cls->getDicount();
        $activity['rewards'] = (string)$market_cls->getRewards();
        $activity['product_type'] = (string)$market_cls->getProductType();
        $activity['channel_type'] = (string)$market_cls->getChannelType();
        $activity['start_time'] = (string)$market_cls->getStartTime();
        $activity['end_time'] = (string)$market_cls->getEndTime();
        $activity['status'] = (string)$market_cls->getStatus();
        $activity['enterprise_id'] = (string)$market_cls->getEnterpriseId();
        $activity['unit'] = (string)$market_cls->getUnit();
        $activity['create_time'] = (string)$market_cls->getCreateAt();
        $activity['edit_time'] = (string)$market_cls->getUpdateAt();
        $activity['update_time'] = (string)$market_cls->getUpdateAt();
        $activity['is_del'] = $market_cls->getIsDel();

        return $activity;
    }

    /*
     * 拼凑在线支付
     * @param  Cls\Pay\Online  $online_cls
     */
    private function pieceOnline($online_list)
    {
        $online = array();
        $online_info = array();
        foreach ($online_list as $online_cls) {
            $online['id'] = $online_cls->getId();
            $online['code'] = $online_cls->getCode();
            $online['name'] = $online_cls->getPayTypeName();
            $online['icon'] = $online_cls->getIcon();
            $online['is_checked'] = $online_cls->getDefault();
            $online_info[] = $online;
        }
        return $online_info;
    }

    /*
     * 拼凑线下支付
     * @param  Cls\Pay\Offline  $offline_cls
     */
    private function pieceOffline($offline_list)
    {
        $offline = array();
        $offline_info = array();
        foreach ($offline_list as $offline_cls) {
            $offline['id'] = $offline_cls->getId();
            $offline['bank_name'] = $offline_cls->getBankName();
            $offline['bank_number'] = $offline_cls->getBankNumber();
            $offline['account'] = $offline_cls->getAccount();
            $offline['is_checked'] = $offline_cls->getDefault();
            $offline_info[] = $offline;
        }
        return $offline_info;
    }

    /*
     * 拼凑流水
     * @param  Cls\Transcation\Transcation  $transcation_cls
     */
    private function piceTranscation($transcation_cls)
    {
        $checkTransaction = array();
        $checkTransaction['id'] = $transcation_cls->getId();
        $checkTransaction['status'] = $transcation_cls->getStatus();
        $checkTransaction['type'] = $transcation_cls->getType();
        $checkTransaction['reference'] = $transcation_cls->getReference();
        $checkTransaction['from'] = $transcation_cls->getFrom();
        $checkTransaction['to'] = $transcation_cls->getTo();
        $checkTransaction['amount'] = $transcation_cls->getAmount();
        $checkTransaction['platform'] = $transcation_cls->getPlatform();
        $checkTransaction['platform_id'] = $transcation_cls->getPlatformId();
        $checkTransaction['create_time'] = $transcation_cls->getCreateTime();
        $checkTransaction['update_time'] = $transcation_cls->getCreateTime();
        $checkTransaction['out_trade_no'] = $transcation_cls->getOutTradeNo();
        return $checkTransaction;
    }

    /*
     * 兼容php5.3的array_column（）
     */
    public function low_array_column($input, $columnKey, $indexKey = NULL)
    {
        $columnKeyIsNumber = (is_numeric($columnKey)) ? TRUE : FALSE;
        $indexKeyIsNull = (is_null($indexKey)) ? TRUE : FALSE;
        $indexKeyIsNumber = (is_numeric($indexKey)) ? TRUE : FALSE;
        $result = array();

        foreach ((array)$input AS $key => $row) {
            if ($columnKeyIsNumber) {
                $tmp = array_slice($row, $columnKey, 1);
                $tmp = (is_array($tmp) && !empty($tmp)) ? current($tmp) : NULL;
            } else {
                $tmp = isset($row[$columnKey]) ? $row[$columnKey] : NULL;
            }
            if (!$indexKeyIsNull) {
                if ($indexKeyIsNumber) {
                    $key = array_slice($row, $indexKey, 1);
                    $key = (is_array($key) && !empty($key)) ? current($key) : NULL;
                    $key = is_null($key) ? 0 : $key;
                } else {
                    $key = isset($row[$indexKey]) ? $row[$indexKey] : 0;
                }
            }
            $result[$key] = $tmp;
        }
        return $result;
    }

    public function unsertlizeAttr($attr)
    {
        if ($attr) {
            @$attr = unserialize($attr);
            if ($attr) {
                $tmpString = '';
                foreach ($attr as $i => $j) {
                    $tmpString .= $i . ':' . $j . '，';
                }
            } else {
                $tmpString = '【统一属性】';
            }

            return '【' . rtrim($tmpString, '，') . '】';
        } else {
            return '【统一属性】';
        }
    }
}